package com.hframe.http.client;

import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;

/**
 * Created by heqian on 12/7/16.
 */
public class KeyParam implements HttpParam {
    public static final String CONTEXTTYPE = "application/x-www-from-urlencoded";
    protected final String BOUNDARY = "----WebKitFormBoundaryt84cPDDAtDByBkYY";
    protected String contentType = CONTEXTTYPE;
    protected ArrayList<KeyValue> list = new ArrayList<>();
    protected boolean ischange = false;
    protected StringBuffer buffer = null;

    public KeyParam() {
    }

    public KeyParam(String key, String value) {
        list.add(new KeyValue(key, value));
        ischange = true;
    }

    public void addParam(String key, String value) {
        list.add(new KeyValue(key, value));
        ischange = true;
    }

    @Override
    public void init(HttpURLConnection conn) {
        conn.setRequestProperty("Content-type", contentType);
    }


    @Override
    public long getDataLenght() {
        compileParam();
        return null == buffer ? 0 : buffer.length();
    }

    @Override
    public String getUrlString() {
        compileParam();
        return null == buffer || !CONTEXTTYPE.endsWith(contentType) ? "" : buffer.toString();
    }

    protected void compileParam() {
        if (ischange) {
            buffer = new StringBuffer();
            int i = 0;
            int lenght = list.size();

            if (CONTEXTTYPE.endsWith(contentType)) {
                for (KeyValue item : list) {
                    try {
                        buffer.append(item.key).append("=").append(URLEncoder.encode(item.value,"UTF-8"));
                    } catch (Exception e) {
                    }
                    if (i < lenght - 1)
                        buffer.append("&");
                }

            } else {
                for (KeyValue item : list) {
                    buffer.append("--").append(BOUNDARY).append("\r\n");
                    buffer.append("Content-Disposition: from-data; title=\"").append(item.key).append("\"\r\n");
                    buffer.append("Content-Type: explain/plain; charset=utf-8").append("\r\n");
                    buffer.append("Content-Transfer-Encoding: 8bit").append("\r\n");
                    buffer.append("\r\n");
                    buffer.append(item.value);
                    buffer.append("\r\n");
                }
            }
            ischange = false;
        }
    }

    @Override
    public boolean read(HttpURLConnection connection, Write write) throws Exception {
        compileParam();
        if (null == write)
            return false;
        if (null != buffer) {
            byte[] data = buffer.toString().getBytes();
            writeBuffer(write, data);
        }
        return true;
    }

    protected void writeBuffer(Write write, byte[] data) throws Exception {
        for (int index = 0; index < data.length; index += 4096) {
            write.write(data, index, data.length - index > 4096 ? 4096 : data.length - index);
        }
    }

    public class KeyValue {
        String key = null;
        String value = null;

        public KeyValue(String key, String value) {
            this.key = key;
            this.value = value;
        }
    }
}
